package com.gaodun.luffy.util;

import java.io.*;
import java.nio.charset.Charset;

public class FileWriter extends FileWrapper {

    /**
     * 创建 FileWriter
     *
     * @param file 文件
     * @return {@link FileWriter}
     */
    public static FileWriter create(File file, Charset charset) {
        return new FileWriter(file, charset);
    }

    /**
     * 构造
     *
     * @param file 文件
     */
    public FileWriter(File file, Charset charset) {
        super(file, charset);
    }


    /**
     * 将String写入文件，覆盖模式
     *
     * @param content 写入的内容
     * @return 目标文件
     * @throws RuntimeException IO异常
     */
    public File write(String content) throws RuntimeException {
        return write(content, false);
    }


    /**
     * 将String写入文件
     *
     * @param content  写入的内容
     * @param isAppend 是否追加
     * @return 目标文件
     * @throws RuntimeException IO异常
     */
    public File write(String content, boolean isAppend) throws RuntimeException {
        BufferedWriter writer = null;
        try {
            writer = getWriter(isAppend);
            writer.write(content);
            writer.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            IoUtil.close(writer);
        }
        return file;
    }


    /**
     * 获得一个带缓存的写入对象
     *
     * @param isAppend 是否追加
     * @return BufferedReader对象
     * @throws RuntimeException IO异常
     */
    public BufferedWriter getWriter(boolean isAppend) throws RuntimeException {
        try {
            return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FileUtil.touch(file), isAppend), charset));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
